package mini.statement;

import mini.compiler.CodeGenerator;
import mini.expr.Expr;

import java.util.HashMap;
import java.util.LinkedList;

public class AssignStatement extends Statement {

    private String name;
    private Expr expr;

    public AssignStatement(String id, Expr e ){
    	name = id;
    	expr = e;
    }

    public void eval(HashMap hm, LinkedList var){
		/* add name to the list of variable names */
		if (!var.contains(name))
		    var.add(name);
		hm.put(name,expr.eval(hm));
    }

    /**
     * Code is from slide 11
     * 1. Do what you need to do to evaluate/load expression
     * 2. Load it to the accumulator
     * 3. Store it to the identifier
     */
    public String parse(HashMap hm, LinkedList var) {
    	
    	CodeGenerator cg = new CodeGenerator();
    	
    	// Do what you need to in roder to evaluate/load expression
    	String exprValue = expr.parse(hm);
    	cg.appendCode( expr.parse(hm) );
    	
    	// Load it into the accumulator
    	cg.addLoadAccumulator( expr.getTempVariable() );
    	
    	// Store it to the identifier
    	cg.addStoreAccumulator( name );
    	
    	// Make sure the name is in the symbolic table
    	hm.put(name, null);
    	
    	// And return this code
    	return cg.getCode();
    }

	@Override
	public String toString() {
		return "AssignStatement [name=" + name + ", expr=" + expr + "]";
	}
}
